package com.sxy.service;

import com.sxy.mapper.BrandMapper;
import com.sxy.pojo.Brand;
import com.sxy.util.SqlSessionFactoryUtils;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import java.util.List;

/**
 * @author 宋鑫宇
 * @version 1.0
 */
public class BrandService {
    //获取sqlSession对象
    SqlSessionFactory sqlSessionFactory = SqlSessionFactoryUtils.getSqlSessionFactory();


    /**
     * 查询所有数据
     * */
    public List<Brand> selectAll(){
        //调用BrandMapper.selectAll()方法
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //获取Mapper对象
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
        //执行sql语句
        List<Brand> brands = mapper.selectAll();

        sqlSession.close();
        return brands;
    }
    /**
     * 添加数据
     * */
    public void add(Brand brand){

        //获取SqlSession对象
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //获取Mapper对象
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
        //执行sql语句
        mapper.add(brand);
        //提交事务
        sqlSession.commit();
        //释放资源
        sqlSession.close();
    }
    /**
     * 删除数据
     * */
    public void delete(int id){
        //获取SqlSession对象
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //获取Mapper对象
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
        //执行sql语句
        mapper.deleteById(id);
        //提交事务
        sqlSession.commit();
        //释放资源
        sqlSession.close();
    }
    /**
     * 修改数据，首先根据id查询数据回显到页面
     * */
    //回显数据
    public Brand selectById(int id){
        //获取SqlSession对象
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //获取Mapper对象
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
        //执行sql语句
        Brand brand = mapper.selectById(id);
        //释放资源
        sqlSession.close();
        return brand;
    }
    //修改数据
    public void update(Brand brand){
        //获取SqlSession对象
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //获取Mapper对象
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
        //执行sql语句
        mapper.update(brand);
        //提交事务
        sqlSession.commit();
        //释放资源
        sqlSession.close();
    }
}
